import mongoose from 'mongoose'
import utils from '../utils'
const Users = mongoose.model('Users')

export default async(ctx, next) => {
  let { token } = ctx.request.body
  if (token) {
    const { userName } = await utils.decodeToken(token)
    try {
      let dataTempFilter = ''
      await utils.ifPhoneNum(userName).then(async res => {
        dataTempFilter = { phone: userName }
      }).catch(async e => {
        dataTempFilter = { userName: userName }
      })
      let user = await Users.findOne(dataTempFilter).exec()
      if (user.userName) {
        if ((new Date().getTime() - user.lastAcitveTime.getTime()) > 60 * 1000 * 20) { // 超过20分钟未操作 过期
          return (ctx.body = {
            success: false,
            data: '登录过期'
          })
        } else {
          await Users.findOneAndUpdate(dataTempFilter, { lastAcitveTime: new Date() }).exec()
          await next()
        }
      } else {
        return (ctx.body = {
          success: false,
          data: 'Token已失效'
        })
      }
    } catch (e) {
      return (ctx.body = {
        success: false,
        data: e.message
      })
    }
  } else {
    return (ctx.body = {
      success: false,
      data: '登录过期'
    })
  }
}
